//
//  ClipToMyBoardView.m
//  Bespoke
//
//  Created by Rafale Chang on 12/8/1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ClipToMyBoardView.h"
#import "SelectBudgetCell.h"
#import "AccountMyBoard.h"
#import "AccountBoard.h"
#import "RequestAPIFunction.h"
#import "GDataXMLNode.h"
#import "Split.h"

#define CREATED_BOOK_ID -1
#define SAVETOMYBOARD_API @"http://54.235.166.43/BeSpokeAPI/MyBoard/SaveToMyBoard.php"

@implementation ClipToMyBoardView
@synthesize delegate;
@synthesize TW_MyBoardList, IV_DropDownBG, Bt_BoardSelection, Lab_BookName;
@synthesize AM_MyBoard, Array_List;
@synthesize MM_CurrentMedia, BK_En_object, IVw_Background, Row_selected;

- (void)initArray:(NSMutableArray *)BoardArray {
    
    self.Array_List = [[NSMutableArray alloc] init];
    [self.Array_List addObjectsFromArray:BoardArray];
    [self.Array_List addObject:[[AccountBoard alloc] BoardID:CREATED_BOOK_ID name:@"New Book" ShareGroup:nil]];
    
    [self.TW_MyBoardList reloadData];
}

-(IBAction)SelectButtonPressed:(id)sender {
    TW_MyBoardList.hidden = false;
    IV_DropDownBG.hidden = false;
    
    [UIView animateWithDuration:0.2
                     animations:^{[TW_MyBoardList setAlpha:1]; [IV_DropDownBG setAlpha:1];}
                     completion:^(BOOL finished){ }];
    
}

-(IBAction)CancelPressed:(id)sender {
    [delegate canceltoBoardPress];
}

-(IBAction)SaveButtonPressed:(id)sender {
    
    if (([Lab_BookName.text isEqualToString:@""])||([Lab_BookName.text isEqualToString:@"Which Book to add this to?"])) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please select Book!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    AccountBoard *AB_SelectedBoard = [self.Array_List objectAtIndex:Row_selected];
    NSString *NS_CheckSource;
    
    
        
    //Check source then upload media to server.
    if (([MM_CurrentMedia.NS_Source isEqualToString:@"TPN"])||([MM_CurrentMedia.NS_Source isEqualToString:@"TPN"]))
        NS_CheckSource = [[NSString stringWithFormat:@"<Media ID=\"%d\" MediaType=\"\" WebLink=\"\" Source=\"%@\" Author=\"\" />",
                           MM_CurrentMedia.MediaID,
                           MM_CurrentMedia.NS_Source] stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    
    else if ((![MM_CurrentMedia.MLH_html.NS_htmlTitle isEqualToString:@""])&&(MM_CurrentMedia.MLH_html.NS_htmlTitle!=nil))
        NS_CheckSource = [NSString stringWithFormat:@"<Media BeMediaID=\"%@\" MediaType=\"8\" WebLink=\"%@\" Source=\"%@\" Author=\"%@\"><Text Title=\"%@\" Description=\"%@\" /><Image Type=\"URL\" Width=\"%d\" Height=\"%d\" FileName=\"%@\" /></Media>",
                          MM_CurrentMedia.NS_BeMediaID,
                          [MM_CurrentMedia.WebLink SymbolParseString],
                          MM_CurrentMedia.NS_Source,
                          MM_CurrentMedia.NS_Author,
                          [MM_CurrentMedia.MLH_html.NS_htmlTitle SymbolParseString],
                          [MM_CurrentMedia.MLH_html.NS_htmlDescription SymbolParseString],
                          MM_CurrentMedia.MLH_html.ImageWidth,
                          MM_CurrentMedia.MLH_html.ImageHeight,
                          [MM_CurrentMedia.MLH_html.NS_ImageName SymbolParseString]
                          ];
    else {
        
        NSMutableString* NS_MediaImageXML = [NSMutableString string];
        
        //Parse XML formate.
        NSString *NS_Title_Temp = [MM_CurrentMedia.text.text_title stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
        NSString *NS_Description_Temp = [MM_CurrentMedia.text.text_description stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
        
        if ((MM_CurrentMedia.text.text_title==nil)||([MM_CurrentMedia.text.text_title isEqualToString:@""]))
            NS_Title_Temp=@"";
        if ((MM_CurrentMedia.text.text_description==nil)||([MM_CurrentMedia.text.text_description isEqualToString:@""]))
            NS_Description_Temp=@"";
        if (MM_CurrentMedia.video.video_type==nil)
            MM_CurrentMedia.video.video_type=@"";
        if (MM_CurrentMedia.video.video_filename==nil)
            MM_CurrentMedia.video.video_filename=@"";
        
        
        for (MediaListsImage *MLI_Image in MM_CurrentMedia.imageArray) {
            if (MLI_Image.image_type==nil)
                MLI_Image.image_type=@"";
            if (MLI_Image.image_filename==nil)
                MLI_Image.image_filename=@"";
            
            [NS_MediaImageXML appendString:[[NSString stringWithFormat:@"<Image Type=\"%@\" Width=\"%d\" Height=\"%d\" FileName=\"%@\" />",
                                            MLI_Image.image_type,
                                            MLI_Image.Width,
                                            MLI_Image.Height,
                                            MLI_Image.image_filename] stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"]];
        }

        
        NS_CheckSource = [[NSString stringWithFormat:@"<Media BeMediaID=\"%@\" MediaType=\"6\" WebLink=\"%@\" Source=\"%@\" Author=\"%@\"><Text Title=\"%@\" Description=\"%@\" />%@<Video Type=\"%@\" FileName=\"%@\" /></Media>",
                          MM_CurrentMedia.NS_BeMediaID,
                          MM_CurrentMedia.WebLink,
                          MM_CurrentMedia.NS_Source,
                          MM_CurrentMedia.NS_Author,
                          NS_Title_Temp,
                          NS_Description_Temp,
                          NS_MediaImageXML,
                          MM_CurrentMedia.video.video_type,
                          MM_CurrentMedia.video.video_filename] stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    }
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" Level=\"\" Name=\"%@\" Organization=\"\"><Board ID=\"%d\" Name=\"%@\" ShareGroup=\"\">%@</Board></AccountInfo>",
                                   BK_En_object.userName,
                                   BK_En_object.fullName,
                                   AB_SelectedBoard.BoardID,
                                   AB_SelectedBoard.name,NS_CheckSource]
                        urlString:SAVETOMYBOARD_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
   
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
    
        int Media_ID = [[[[[doc nodesForXPath:@"//Success" error:nil] objectAtIndex:0] attributeForName:@"MediaID"] stringValue] integerValue];
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Media was successfully added to the Book." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        
        MM_CurrentMedia.MediaID = Media_ID;
        [AB_SelectedBoard.MediaArray addObject:MM_CurrentMedia];
        MediaListsMedia *test =[AB_SelectedBoard.MediaArray objectAtIndex:[AB_SelectedBoard.MediaArray indexOfObject:MM_CurrentMedia]];
        NSLog(@"%@",test);
        [delegate saveToBoardPress];
    }
    else if ([[doc nodesForXPath:@"//Error" error:&error] count]!=0) {
        
        NSString *NS_Message = [[[[doc nodesForXPath:@"//Error" error:nil] objectAtIndex:0] attributeForName:@"Message"] stringValue];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:NS_Message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        return;
    }
}

#pragma mark - UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *ButtonCellIdentifier = @"SelectBudgetCell";
    SelectBudgetCell *TVwC_SelectCell = [tableView dequeueReusableCellWithIdentifier:ButtonCellIdentifier];
    
    UIView *bgColorView = [[UIView alloc] init];
    UIColor *UC_skyblue= [UIColor colorWithRed:206.0/255.0 green:235.0/255.0 blue:236.0/255.0 alpha:1.0];
    [bgColorView setBackgroundColor:UC_skyblue];
    
    if (TVwC_SelectCell == nil) {
        
        NSArray *Array_nib = [[NSBundle mainBundle] loadNibNamed:@"SelectBudgetCell" owner:nil options:nil];
        
        TVwC_SelectCell = [Array_nib objectAtIndex:0];

        [TVwC_SelectCell setSelectedBackgroundView:bgColorView];
    }
    
    AccountBoard *Board = [self.Array_List objectAtIndex:indexPath.row];
    TVwC_SelectCell.Lab_Price.text = Board.name;
    
    if ([TVwC_SelectCell.Lab_Price.text isEqualToString:@"New Book"]) {
        TVwC_SelectCell.IVw_Symbol.hidden = NO;
        TVwC_SelectCell.Lab_Price.frame = CGRectMake(TVwC_SelectCell.IVw_Symbol.frame.origin.x+TVwC_SelectCell.IVw_Symbol.frame.size.width,
                                                     TVwC_SelectCell.frame.origin.y,
                                                     TVwC_SelectCell.frame.size.width,
                                                     TVwC_SelectCell.frame.size.height);
    }
    
    return TVwC_SelectCell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.Array_List count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [UIView animateWithDuration:0.2
                     animations:^{[tableView setAlpha:0]; [IV_DropDownBG setAlpha:0];}
                     completion:^(BOOL finished){ }];
    
    if (((AccountBoard *)[self.Array_List objectAtIndex:indexPath.row]).BoardID==CREATED_BOOK_ID)
        [self.delegate CreatedNewBookPressed];
    else {
        
        Lab_BookName.text = ((AccountBoard *)[self.Array_List objectAtIndex:indexPath.row]).name;
        Row_selected = indexPath.row;
    }
}

@end
